export class UploadFile {
  constructor(file, id = null, type = 'file') {
    this.id = id || this.generateId();
    this.file = file;
    this.name = file.name;
    this.size = file.size;
    this.type = type;
    this.originalType = file.type;
    this.progress = 0;
    this.status = 'pending'; // pending, uploading, completed, error, cancelled
    this.uploadSpeed = 0;
    this.estimatedTime = 0;
    this.createdAt = new Date();
    this.error = null;
    this.previewUrl = null;

    // 生成预览URL（如果是图片或视频）
    if (file.type.startsWith('image/') || file.type.startsWith('video/')) {
      this.previewUrl = URL.createObjectURL(file);
    }
  }

  generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  }

  updateProgress(progress, uploadSpeed = 0) {
    this.progress = Math.min(progress, 100);
    this.uploadSpeed = uploadSpeed;

    if (uploadSpeed > 0 && progress < 100) {
      const remainingBytes = this.size * (1 - progress / 100);
      this.estimatedTime = remainingBytes / uploadSpeed;
    }

    if (progress >= 100) {
      this.status = 'completed';
      this.estimatedTime = 0;
    }
  }
  // 设置上传状态
  setStatus(status, error = null) {
    this.status = status;
    this.error = error;

    if (status === 'uploading' && this.progress === 0) {
      this.progress = 1;
    } else if (status === 'completed') {
      this.progress = 100;
    }
  }

  cancel() {
    if (this.status === 'uploading') {
      this.status = 'cancelled';
      // 清理预览URL
      if (this.previewUrl) {
        URL.revokeObjectURL(this.previewUrl);
      }
    }
  }

  toJSON() {
    return {
      id: this.id,
      name: this.name,
      size: this.size,
      type: this.type,
      progress: this.progress,
      status: this.status,
      uploadSpeed: this.uploadSpeed,
      estimatedTime: this.estimatedTime,
      createdAt: this.createdAt,
      previewUrl: this.previewUrl
    };
  }
}